/**
 * 原子性值得注意的地方（二)
 * 2019年 01月 02日 星期三
 *
 * @author fireway
 */
package concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class CircularSet {
    private int [] mArray;

    private int mIndex;

    public CircularSet(int initialCapacity) {
        mArray = new int[initialCapacity];

        for (int i = 0; i < initialCapacity; i++) {
            mArray[i] = -1;
        }
    }

    public synchronized void add(int data) {
        mArray[mIndex] = data;
        mIndex++;
        mIndex = mIndex % mArray.length;
    }

    public synchronized boolean contains(int data) {
        for (int i = 0; i < mArray.length; i++) {
            if (data == mArray[i]) {
                return true;
            }
        }
        return false;
    }
}

public class SerialNumberChecker {
    private static final int SIZE = 10;

    private static ExecutorService sExec = Executors.newCachedThreadPool();

    private static CircularSet sSet = new CircularSet(1000);

    static class SerialChecker implements Runnable {

        @Override
        public void run() {
            while(true) {
                int data = SerialNumberGenerator.nextSerialNumber();
                if (sSet.contains(data)) {
                    System.out.println("Duplicate: " + data + " in " + Thread.currentThread());
                    System.exit(0);
                }
                sSet.add(data);
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < SIZE; i++) {
            sExec.execute(new SerialChecker());

        }
    }
}
